package tools.project.controller {
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;
	
	import ghostcat.fileformat.png.PNGEncoder;
	
	import kiwi.action.queue.Queue;
	import kiwi.debug.Log;
	import kiwi.event.ActionEvent;
	import kiwi.util.ArrayUtils;
	import kiwi.util.bitmap.BitmapUtil;
	
	import org.aswing.JOptionPane;
	import org.robotlegs.mvcs.Command;
	
	import tools.event.ProjectEvent;
	import tools.model.ActionFrameInfo;
	import tools.model.ActionInfo;
	import tools.model.EditorConfig;
	import tools.model.FrameInfo;
	import tools.model.TextureBitmap;
	import tools.model.TextureTypeEnum;
	import tools.model.TileInfo;
	import tools.utils.MaxRectsBinPack;

	/**
	 * 从文件夹导入工程
	 * 文件夹的结构如此
	 * /--config.xml	// 配置文件
	 * 	|-{动作名}/		// 动画的动作名字(idle)
	 * 		|-1/		// 动画的帧id(从1开始)
	 * 		|	|-1.png	// 动画帧的tile
	 * 		|-2.png		// 如果没有多个tile也可以直接用一个文件代替
	 * @author zhangming.luo
	 */
	public class ImportProjectCommand extends Command {
		[Inject]
		public var config : EditorConfig;
		[Inject]
		public var event : ProjectEvent;
		private var rootDir : File;
		private var root : String;
		private var frameId : int = 0;
		private var queue : Queue;
		private var actions : Array = [];
		private var frames : Array = [];
		private var tiles : Array = [];
		private var dictionary:Dictionary;
		private var childDicList:Array;

		override public function execute() : void {
			super.execute();
			if (event.file) {
				rootDir = event.file;
				onSelected();
			} else {
				JOptionPane.showInputDialog("提示", "打开动画的所在目录", function(path : String) : void {
					if (!path) {
						return;
					}
					rootDir = File.applicationDirectory.resolvePath(path);
					if (!rootDir.exists) {
						Log.alert("目录不存在");
					} else if (!rootDir.isDirectory) {
						Log.alert("请选择文件夹");
					} else {
						onSelected();
					}
				},"e:\\Desktop\\mengjiang");
			}
		}

		private function onSelected(event : Event = null) : void {
			queue = new Queue();
			dictionary = new Dictionary();
			childDicList = [];
			root = rootDir.nativePath;
			var files : Array = rootDir.getDirectoryListing();
			for each (var file:File in files) {
				if (file.isDirectory && file.name.indexOf(".") != 0) {
					var action : ActionInfo = new ActionInfo();
					action.name = file.name;
					loadAction(action, file);
					actions.push(action);
				} else if (file.name == "config.xml") {
					loadConfig(file);
				}
			}
			queue.addEventListener(ActionEvent.ACTION_COMPLETE, onComplete);
			queue.execute();
		}

		
		private function loadAction(action : ActionInfo, dir : File) : void {
			var files : Array = dir.getDirectoryListing();
			///------------------------------------
			// save文件夹以及旗下的。png
			var pngList:Array = new Array();
			///------------------------------------
			for (var i : int = 1;true;i++) {
				var file : File = ArrayUtils.findFirst(files, function(f : File) : Boolean {
					if (f.isDirectory && f.name == i.toString()) {
						return true;
					} else if (!f.isDirectory && f.name.toString() == i + ".png") {
						return true;
					}
					return false;
				});
				if (file == null) {
					break;
				}
				var frame : FrameInfo = new FrameInfo();
				frame.id = ++frameId;
				frame.name = file.name;
				if (file.isDirectory) {
					loadTile(frame, file);
				} else {
					var tileAction : ReadTileAction = new ReadTileAction(file);
					queue.submit(tileAction);
					frame.tileList.push(tileAction.tile);
					tiles.push(tileAction.tile);
					pngList.push(tileAction.tile);
				}
				frame.name = file.name;
				frames.push(frame);
				var info : ActionFrameInfo = new ActionFrameInfo();
				info.frame = frame;
				info.duration = 1;
				action.frameList.push(info);
			}
			//  --
			childDicList.push(dir.name);
			dictionary[dir.name] = pngList;
		}

		private function onComplete(e : Event) : void {
			// 重组Texture
			var pack : MaxRectsBinPack = new MaxRectsBinPack(4096, 4096);
			var dic : Dictionary = new Dictionary();
			var tile : TileInfo;
			for each (tile in tiles) {
				var tmp : Rectangle = pack.insert(tile.source.width, tile.source.height, MaxRectsBinPack.METHOD_RECT_BEST_AREA_FIT);
				dic[tile] = tmp;
				tile.source.x = tmp.x;
				tile.source.y = tmp.y;
			}
			// 绘制Texture
			var canvas : BitmapData = new BitmapData(4096, 4096, true, 0x0);
			canvas.lock();
			for each (tile in tiles) {
				canvas.copyPixels(tile.$cached, tile.$cached.rect, Rectangle(dic[tile]).topLeft, null, null, true);
			}
			canvas.unlock();
			canvas = BitmapUtil.trim(canvas, null);
			var textureFile : File = File.applicationDirectory.resolvePath(root + "/texture.png");
			var output : FileStream = new FileStream();
			output.open(textureFile, FileMode.WRITE);
			output.writeBytes(PNGEncoder.encode(canvas));
			output.close();
			config.texture = new TextureBitmap();
			config.texture.file = textureFile.nativePath;
			config.texture.bitmapData = canvas.clone();
			for each (tile in tiles) {
				tile.$source = config.texture;
			}
			for each (var frame:FrameInfo in frames) {
				frame.$source = config.texture;
			}
			config.allTileList = tiles;
			config.allFrameList = frames;
			config.actionList = actions;
			
			// 解析文件夹以及旗下的。png 并绘图
//			var tempCanvas : BitmapData;
//			var tempFile : File;
//			var tempOP:FileStream;
			
			
//			var eachKeyDic:Dictionary = new Dictionary();
//			var keyDic : Dictionary = new Dictionary();
//			
//			for each(var key:String in childDicList){
//				if(TextureTypeEnum.BATTLES.indexOf(key)>=0){  //
//					if(eachKeyDic["battles"]&&eachKeyDic["battles"] is Array){
//						eachKeyDic["battles"] = (eachKeyDic["battles"] as Array).concat(dictionary[key]);
//					}else{
//						eachKeyDic["battles"] = dictionary[key];
//						keyDic["battles"] = "battles";
//					}
//				}else if(TextureTypeEnum.STILLS.indexOf(key)>=0){
//					if(eachKeyDic["stills"]&&eachKeyDic["stills"] is Array){
//						eachKeyDic["stills"] = (eachKeyDic["stills"] as Array).concat(dictionary[key]);
//					}else{
//						eachKeyDic["stills"] = dictionary[key];
//						keyDic["stills"] = "stills";
//					}
//				}else{
//					if(eachKeyDic["others"]&&eachKeyDic["others"] is Array){
//						eachKeyDic["others"] = (eachKeyDic["others"] as Array).concat(dictionary[key]);
//					}else{
//						eachKeyDic["others"] = dictionary[key];
//						keyDic["others"] = "others";
//					}
//				}
//			}
//			
//			for each(var arrKey:Object in keyDic){
//				if(arrKey && eachKeyDic[arrKey] is Array){
//					tempCanvas = new BitmapData(4096, 4096, true, 0x0);
//					tempCanvas.lock();
//					for each(tile in eachKeyDic[arrKey]){
//						tempCanvas.copyPixels(tile.$cached, tile.$cached.rect, Rectangle(dic[tile]).topLeft, null, null, true);
//					}
//					tempCanvas.unlock();
//					tempCanvas = BitmapUtil.trim(tempCanvas,null);
//					
//					tempFile = File.applicationDirectory.resolvePath(root + "/"+ arrKey +".png");
//					tempOP = new FileStream();
//					tempOP.open(tempFile, FileMode.WRITE);
//					tempOP.writeBytes(PNGEncoder.encode(tempCanvas));
//					tempOP.close();
//				}
//			}
			
					
			if (!event.ignorInfo) {
				Log.alert("导入成功");
			}
			dispatch(new ProjectEvent(ProjectEvent.SAVE, false, false, rootDir.resolvePath(rootDir.name.replace(/^[^_]+_(.+)/, "$1") + ".sprite")));
			dispatch(new ProjectEvent(ProjectEvent.IMPORT_COMPLETE));
		}

		private function loadTile(frame : FrameInfo, dir : File) : void {
			var files : Array = dir.getDirectoryListing();
			for each (var file:File in files) {
				var tileAction : ReadTileAction = new ReadTileAction(file);
				queue.submit(tileAction);
				tiles.push(tileAction.tile);
				frame.tileList.push(tileAction.tile);
			}
		}

		private function loadConfig(file : File) : void {
		}
	}
}
import kiwi.action.Action;
import kiwi.util.bitmap.BitmapUtil;

import tools.model.TileInfo;

import flash.display.Bitmap;
import flash.display.Loader;
import flash.events.Event;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.ByteArray;

class ReadTileAction extends Action {
	public static var id : int = 0;
	public var tile : TileInfo = new TileInfo();
	private var file : File;
	private var loader : Loader;

	public function ReadTileAction(file : File) {
		this.file = file;
		tile.id = ++id;
	}

	override public function execute() : void {
		super.execute();
		var input : FileStream = new FileStream();
		input.open(file, FileMode.READ);
		var data : ByteArray = new ByteArray();
		input.readBytes(data);
		input.close();
		loader = new Loader();
		loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
		loader.loadBytes(data);
	}

	private function onComplete(event : Event) : void {
		tile.name = file.name;
		var trimBounds : Rectangle = new Rectangle();
		tile.$cached = BitmapUtil.trim(Bitmap(loader.content).bitmapData, trimBounds, false);
		if (Bitmap(loader.content).bitmapData.width == 1024 && Bitmap(loader.content).bitmapData.height == 1024) {
			tile.registration = new Point(512 - trimBounds.left, 512 - trimBounds.top);
		} else {
			tile.registration = new Point(256 - trimBounds.left, 256 - trimBounds.top);
		}
		tile.source = new Rectangle(0, 0, trimBounds.width, trimBounds.height);
		result();
	}
}